"""操作系统信息"""
import os
import psutil
import platform
import subprocess
from src.utils.deep import get_os_info
from src.core.variables.status import *
from src.core.variables.function import *


def __get_linux_distribution():
    """获取Linux发行版信息"""
    # 尝试使用 /etc/os-release 文件
    if os.path.exists("/etc/os-release"):
        with open("/etc/os-release") as f:
            lines = f.readlines()
            info = {}
            for line in lines:
                if "=" in line:
                    key, value = line.strip().split("=", 1)
                    info[key] = value.strip('"')
            
            if "PRETTY_NAME" in info:
                return info["PRETTY_NAME"]
            elif "NAME" in info and "VERSION" in info:
                return f"{info['NAME']} {info['VERSION']}"
    
    # 尝试使用 platform.freedesktop_os_release (Python 3.10+)
    try:
        import platform
        if hasattr(platform, 'freedesktop_os_release'):
            info = platform.freedesktop_os_release()
            if "PRETTY_NAME" in info:
                return info["PRETTY_NAME"]
            elif "NAME" in info and "VERSION" in info:
                return f"{info['NAME']} {info['VERSION']}"
    except:
        pass
    
    # 尝试使用 lsb_release 命令
    try:
        result = subprocess.run(["lsb_release", "-d"], capture_output=True, text=True)
        if result.returncode == 0:
            desc = result.stdout.strip().split(":", 1)[1].strip()
            return desc
    except:
        pass
    
    # 尝试读取常见的发行版标识文件
    dist_files = [
        ("/etc/debian_version", "Debian GNU/Linux"),
        ("/etc/redhat-release", None),
        ("/etc/centos-release", None),
        ("/etc/fedora-release", None),
        ("/etc/gentoo-release", None),
        ("/etc/SuSE-release", None),
        ("/etc/arch-release", "Arch Linux"),
    ]
    
    for file_path, prefix in dist_files:
        if os.path.exists(file_path):
            try:
                with open(file_path) as f:
                    content = f.read().strip()
                    if prefix:
                        return f"{prefix} {content}"
                    else:
                        return content
            except:
                pass
    
    return "Unknown Linux"


def system_info():
    # 获取系统信息
    os_name = platform.system()
    os_release = platform.release()
    
    # 获取操作系统发行版信息
    if os_name == "Linux":
        os_info = __get_linux_distribution()
    else:
        os_info = f"{os_name} {os_release}"
    
    # 获取CPU信息
    cpu_count = psutil.cpu_count()
    cpu_model = platform.processor() or "未知"
    
    # 获取内存信息
    memory_info = psutil.virtual_memory()
    memory_total = memory_info.total
    
    # 格式化内存大小显示
    if memory_total >= (1024**3):  # GB
        memory_str = f"{memory_total / (1024**3):.1f} GiB"
    elif memory_total >= (1024**2):  # MB
        memory_str = f"{memory_total / (1024**2):.1f} MiB"
    else:  # KB
        memory_str = f"{memory_total / 1024:.1f} KiB"
    
    # 获取运行时间信息
    boot_time = psutil.boot_time()
    current_time = get_os_info.local_time("timestamp") / 1000  # 转换为秒
    uptime_seconds = int(current_time - boot_time)
    
    # 格式化运行时间显示
    days = uptime_seconds // (24 * 3600)
    hours = (uptime_seconds % (24 * 3600)) // 3600
    minutes = (uptime_seconds % 3600) // 60
    uptime_info = f"{days}天 {hours}小时 {minutes}分钟"
    
    # 尝试识别默认包管理器
    pkg_manager = "未知"
    if os_name == "Linux":
        # 检查常见的Linux包管理器
        package_managers = [
            ("apt", "/usr/bin/apt"),
            ("yum", "/usr/bin/yum"),
            ("dnf", "/usr/bin/dnf"),
            ("pacman", "/usr/bin/pacman"),
            ("zypper", "/usr/bin/zypper"),
            ("apk", "/sbin/apk"),
            ("brew", "/home/linuxbrew/.linuxbrew/bin/brew")
        ]
        
        for name, path in package_managers:
            if os.path.exists(path):
                pkg_manager = name
                break
    
    result = [
        {"name": "操作系统", "value": os_info},
        {"name": "内核版本", "value": os_release},
        {"name": "运行时间", "value": uptime_info},
        {"name": "默认包管理器", "value": pkg_manager},
        {"name": "CPU型号", "value": cpu_model},
        {"name": "架构", "value": platform.machine()},
        {"name": "CPU核数", "value": str(cpu_count)},
        {"name": "内存", "value": memory_str},
    ]
    return result